package com.hmall.pojo;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.item.Item;
import com.hmall.mapper.TestItemMapper;
import com.hmall.search.ItemDoc;
import lombok.Data;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.List;


/**
 * @author HOLO
 * @create 2023-01-06 18:20
 * @discription
 */
@Data
public class JoinDataThread implements Runnable {

    //索引库名
    private String index_name;
    //从查询当前页
    private Integer pageIndex;
    //页显示数
    private Integer size;
    private RestHighLevelClient highLevelClient;
    private TestItemMapper itemMapper;


    public JoinDataThread(TestItemMapper itemMapper, String index_name, RestHighLevelClient highLevelClient, Integer pageIndex, Integer size) {
        this.index_name = index_name;
        this.pageIndex = pageIndex;
        this.highLevelClient = highLevelClient;
        this.size = size;
        this.itemMapper = itemMapper;
    }


    @Override
    public void run() {
        Page<Item> page = new Page<>(pageIndex, size);
        //定义查询条件 status = 1
        LambdaQueryWrapper<Item> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Item::getStatus, 1);
        //调用selectPage方法实现分页，分页的结果会被封装到Page对象中
        itemMapper.selectPage(page, wrapper);
        List<Item> itemList = page.getRecords();
        //2.判断集合是否不为空，工具类 CollectionUtils.isNotEmpty(集合)
        if (CollectionUtils.isNotEmpty(itemList)) {
            //3.创建批量操作请求对象 BulkRequest
            BulkRequest bulkRequest = new BulkRequest();
            //4.遍历 List<Hotel> 集合每元素数据
            for (Item item : itemList) {
                //4.1.将每个 item 对象封装层 hotelDoc 对象
                ItemDoc itemDoc = new ItemDoc(item);
                //4.2 根据ItemDoc对象数据，构建添添加文档数据的请求对象 IndexRequest 对象
                //    本质：构建每个数据的添加文档命令，格式为: POST 索引库名/_doc
                IndexRequest request = new IndexRequest(index_name).id(item.getId().toString());
                //4.3 将 hotelDoc 对象转换为json字符串，并通过request对象source方法封装json数据
                //    本质：构建每个数据的添加文档命令，格式为: POST 索引库名/_doc{文档数据}
                request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
                //4.4 将请求对象 IndexRequest(每个添加文档命令) 添加到批量操作请求对象 BulkRequest 中
                bulkRequest.add(request);
            }
            //5.批量执行添加命令
            try {
                highLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
